<?php
class DB
{
	var $db;
    var $write_log = false;
	function __construct($host,$user,$password,$dbname,$port='3306'){
		$host .= ':' . $port;
		$this->db = @mysql_connect($host,$user,$password);
		if (!$this->db){
			$this->write_err_log($host, mysql_error());
			// 重试
			$this->db = @mysql_connect($host,$user,$password);
			if (!$this->db){
				$this->write_err_log($host, mysql_error(), 'retry');
				return false;
			}
		}
		mysql_select_db($dbname, $this->db);
		mysql_query("set names 'utf8'");
		return true;
	}

	function closs(){
		mysql_close($this->db);
	}

	function query($sql){
		$query_result = mysql_query($sql, $this->db);
		if ($query_result === true){ // 执行 insert update replace 等的结果
			$re = true;
		}elseif($query_result === false){ // sql执行错误
			$re = false;
			$this->write_err_log('unknown!', mysql_error(), 'query');
		}else{ // 执行 select 的结果
			$re = array();
			$row = mysql_fetch_array($query_result, MYSQL_ASSOC);
			while($row){
				$re[] = $row;
				$row = mysql_fetch_array($query_result, MYSQL_ASSOC);
			}
		}
		return $re;
	}
	
	function last_id(){
		return mysql_insert_id($this->db);
	}

	// 数据库错误日志
	function write_err_log($host, $info, $type='conn'){
        return true;
        if (!$this->write_log) return true;

		$time = date('Y-m-d H:i:s');
		$log_str = "HOST:{$host}\tINFO:{$info}\tTIME:{$time}\tTYPE:{$type}\n";
		$logpath = '/data0/weibo_scripts/dberrlog/' . date('Ym/');
		if (!file_exists($logpath)){
			@mkdir($logpath, 777, true);
		}
		@file_put_contents($logpath.'errlog', $log_str, FILE_APPEND);
		return true;
	}
}


// 连接touzhu库
function db_touzhu() {
    global $DBCONF;
	return new DB($DBCONF['HOST'], $DBCONF['USER'], $DBCONF['PASSWORD'], $DBCONF['DB']);
}

// 滚球数据写表
function write_ball_disc($db, $matchs){
	$re_match = array();
	if (is_array($matchs) && !empty($matchs)){
		foreach ($matchs as $match){
			$add_time = date('Y-m-d H:i:s');
			$sql = 'insert into ball_disc (`from`, match_id, match_time, match_name, home_team, visiting_team, home_team_id, ';
			$sql .= 'visiting_team_id, wanfa, pankou, over, under, just, link, fetch_time, add_time) ';
			$sql .= "values({$match['from']}, '{$match['match_id']}', '{$match['match_time']}', '{$match['match_name']}', ";
			$sql .= "'{$match['home_team']}', '{$match['visiting_team']}', {$match['home_team_id']}, {$match['visiting_team_id']}, ";
			$sql .= "'{$match['wanfa']}', '{$match['pankou']}', '{$match['over']}', '{$match['under']}', '{$match['just']}',";
			$sql .= " '{$match['link']}', '{$match['fetch_time']}', '{$add_time}');";

			$re = $db->query($sql);
			if ($re){
				$match['id'] = $db->last_id();
				$re_match['succ_match'][] = $match;
			}else {
				$re_match['err_match'][] = $match;
			}
		}
	}
	return $re_match;
}

// 根据id取滚球数据
function get_match_by_id($db, $id){
	$sql = 'select * from ball_disc where id=' . $id;
	$re = $db->query($sql);
	return isset($re[0]) ? $re[0] : false;
}

// 球队名写表
function write_teams($db, $teams, $from, $_188bet_id = 0, $type = 1){
	$ids = array();
	if (is_array($teams) && !empty($teams)){
		foreach ($teams as $team){
			$add_time = date('Y-m-d H:i:s');
			$sql = 'insert into teams (188bet_id, team, `from`, `type`, add_time) ';
			$sql .= "values({$_188bet_id}, '{$team}', {$from}, {$type}, '{$add_time}')";
			$re = $db->query($sql);
			if ($re){
				if ($from == 2){
					$ids[$team] = 0; // 新加的bet188球队，id为0
				}else {
					$ids[$team] = $db->last_id();
				}
			}
		}
	}
	return $ids;
}

// $form 1.bet365 2.188bet
function read_teams($db, $from, $starttime = '', $endtime = ''){
	$where = "where `from`={$from} ";
	if (!empty($starttime)){
		$where .= "and add_time>='{$starttime}' ";
	}
	if (!empty($endtime)){
		$where .= "and add_time<='{$endtime}' ";
	}
	$sql = 'select bet365_id, 188bet_id, team, `from`, type, add_time from teams ' . $where;
	$sql .= "order by bet365_id desc";
	return $db->query($sql);
}

// 根据球队名取id
function read_team_id($db, $teams, $from, $type = 1){
	foreach ($teams as &$team){
		$team = "'{$team}'";
	}
	$teams_str = implode(',', $teams);
	$sql = 'select bet365_id, 188bet_id, team, `from`, type, add_time from teams ';
	$sql .= "where `from`={$from} and team in ({$teams_str})";
	return $db->query($sql);
}
